﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace Copy5x
{
    class ErrorLog
    {
        private DirectoryInfo Folder;
        private XDocument statusDoc;
        private string statusFilePath = string.Empty;

        public ErrorLog(string folder)
        {
            Folder = new DirectoryInfo(folder);
            
            if( ! Folder.Exists)
                throw new Exception("Folder not found : " + folder);

            initStatusFile();
        }

        private void initStatusFile()
        {
            statusFilePath = Folder.FullName + Path.DirectorySeparatorChar + "copystatus.xml";

            FileInfo statusFile = new FileInfo(statusFilePath);

            if (!statusFile.Exists)
            {
                XDocument newStatus = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement("status",
                        new XElement("files")                        
                         )
                     );

                newStatus.Save(statusFilePath);
            }

            statusDoc = XDocument.Load(statusFilePath);
        }
        public void AddError(string fileName, string msg)
        {
            var statusNodes = from file in statusDoc.Descendants("file")
                              where (string)file.Attribute("name") == fileName
                              select (XElement)file;

            if (statusNodes.Count() == 0)
            {

                statusDoc.Descendants("files").Last().Add
                    (
                    new XElement("file",
                        new XAttribute("name", fileName),                        
                        new XCData(msg)
                        )
                    );

            }
            else
            {
                foreach (XElement statusNode in statusNodes)
                {                    
                    statusNode.SetValue(new XCData(msg).Value);
                }
            }

            statusDoc.Save(statusFilePath);
        }
    }
}
